<?php

namespace app\admin\controller\goods;

use app\admin\model\goods\GoodsSpec;
use app\common\controller\Backend;
use app\common\model\Category;
use app\common\model\goods\GoodsModel;
use Exception;
use fast\Tree;
use PDOException;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 规格属性
 *
 * @icon fa fa-circle-o
 */
class GoodsSpecGroup extends Backend
{

    /**
     * GoodsSpecGroup模型对象
     * @var \app\admin\model\goods\GoodsSpecGroup
     */
    protected $model = null;
    protected $noNeedRight = ['getSpecGroup'];
    protected $categorylist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\GoodsSpecGroup;
        $this->view->assign("goodsSpecTypeList", $this->model->getGoodsSpecTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $tree = Tree::instance();
        $tree->init(collection(Category::order('weigh desc,id desc')->field('id,pid,name')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */



    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $admin_cate_ids = explode(',',$row->admin_cate_ids);
                if($admin_cate_ids){
                    $admin_cate_ids_arr = [];
                    foreach ($admin_cate_ids as $val){
                        $admin_cate_id_arr = Tree::instance($this->categorylist)->getParentsName($val,true);
                        $admin_cate_ids_arr[] = implode('/',$admin_cate_id_arr);
                    }
                    $row->admin_cate_ids_text = implode('<br>',$admin_cate_ids_arr);
                }
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $params['admin_cate_ids'] = $this->getAdminCateIdsParentsIdsChildrenIds($params['admin_cate_ids']);

            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }

            $new_admin_cate_ids = $params['admin_cate_ids'] = $this->getAdminCateIdsParentsIdsChildrenIds($params['admin_cate_ids']);

            $old_admin_cate_ids = $row->admin_cate_ids;

            $diff_admin_cate_ids = array_diff(explode(',',$old_admin_cate_ids),explode(',',$new_admin_cate_ids));

            $admin_cate_ids = [];

            if(!empty($diff_admin_cate_ids)){
                $admin_cate_ids = $diff_admin_cate_ids;
            }

            if($params['status'] == 0){
                $admin_cate_ids = explode(',',$old_admin_cate_ids);
            }

            if(!empty($admin_cate_ids)){
                $goods_count = GoodsModel::where('status','=','up')
                    ->whereIn('cate_id',$admin_cate_ids)
                    ->whereNull('deletetime')
                    ->count();
                if($goods_count > 0){
                    Exception('有正在上架中的商品,请下架后重试');
                }
            }

            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        // 搜索规格项ID集
        $goods_spec_item_ids = \app\admin\model\goods\GoodsSpecItem::whereIn('spec_group_id',$ids)->column('spec_item_id');
        if($goods_spec_item_ids){
            $FIND_IN_SET = [];
            foreach ($goods_spec_item_ids as $val){
                $FIND_IN_SET[] = "FIND_IN_SET('$val',`spec_item_key`)";
            }
            // 用or是匹配任意条件符合的
            $FIND_IN_SET = implode(' or ',$FIND_IN_SET);
            // 用and是匹配全部条件符合的
//            $FIND_IN_SET = implode(' and ',$FIND_IN_SET);
//            ->whereRaw($FIND_IN_SET)
            $goods_ids = GoodsSpec::whereRaw($FIND_IN_SET)
                ->whereNull('deletetime')
                ->where('status',1)
                ->column('goods_id');
            if($goods_ids){
                // 搜索有没有正在上架的产品
                $goods_count = \app\admin\model\goods\Goods::whereIn('id',$goods_ids)
//                    ->withSum('spec','spec_stock')
                    ->where('status','up')
                    ->whereNull('deletetime')
                    ->count();
                if($goods_count > 0){
                    $this->error('删除失败,有正在上架中的商品');
                }
            }
        }

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 获取当前选择关联后台类目的所有父级ID和子集ID
    */
    public function getAdminCateIdsParentsIdsChildrenIds($admin_cate_ids): string
    {
        $admin_cate_ids = explode(',',$admin_cate_ids);
        $admin_cate_ids_arr = [];
        foreach ($admin_cate_ids as $val){
            $admin_cate_ids_arr = array_merge($admin_cate_ids_arr,Tree::instance($this->categorylist)->getParentsIds($val,true));
//            $admin_cate_ids_arr = array_merge($admin_cate_ids_arr,Tree::instance($this->categorylist)->getChildrenIds($val,true));
        }
        $admin_cate_ids_arr = array_unique($admin_cate_ids_arr,SORT_NUMERIC);
        sort($admin_cate_ids_arr);
        return implode(',',$admin_cate_ids_arr);
    }

    /**
     * 获取规格属性
     * @param int $cate_id
     * @return string 返回表格字符串
     */
    public function getSpecGroup()
    {
        $cate_id = $this->request->post("cate_id");
        if(empty($cate_id)){
            $this->error(__('Parameter %s can not be empty', 'cate_id'));
        }

        $spec = $this->model
            ->whereRaw("FIND_IN_SET('$cate_id',`admin_cate_ids`)")
            ->where(['status' => 1])
//            ->whereNotIn('goods_spec_type',['key'])
            ->select();
        if(!$spec){
            $this->error(__('No Results were found'));
        }
        $this->success('请求成功','',$spec);

//        $str = "<button type='button' class='spec btn btn-success' id='addSpecInput'>增加属性</button>";
//        $str .= "<table class='table table-striped table-bordered table-hover table-nowrap'>";
//        $str .="<thead>";
//        $str .="<tr>";
//        $str .="<td><b>序号</b></td>";
//        foreach ($spec as $row)
//        {
//            $str .= "<td><b>$row->spec_name</b></td>";
//        }
//        $str .= "
//                <td><b>价格</b></td>
//                <td><b>库存</b></td>
//                <td><b>单位</b></td>
//                <td><b>重量(kg)</b></td>
//                <td><b>编码</b></td>
//                <td><b>图片</b></td>
//                <td><b>操作</b></td>
//             </tr>";
//        $str .="</thead>";
//
//        $str .="<tbody id='spec_input_tab'>";
//        $str .="</tbody>";
//
//        $str .= "</table>";
//        return $str;
    }

}
